package com.dong.controller;

import com.dong.base.BaseController;
import com.dong.entity.Region;
import com.dong.entity.User;
import com.dong.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController extends BaseController {

    @Autowired
    UserService userService;

    @InitBinder("user")
    public void initUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("user.");
    }

    @InitBinder("region")
    public void initRegion(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("region.");
    }

    @RequestMapping("/queryAllUser")
    public Object queryAllUser() {
        return userService.queryAllUser();
    }

    @RequestMapping("/queryUserById")
    public Object queryUserById(String id) {
        return userService.queryUserById(id);
    }

    @RequestMapping("/queryUserByUsername")
    public Object queryUserByUsername(String username) {
        return userService.queryUserByUsername(username);
    }

    @RequestMapping("/insertUser")
    @RequiresPermissions("second:yes")
    public Object insertUser(User user, Region region) {
        return userService.insertUser(user);
    }

    @RequestMapping("/updateUser")
    public Object updateUser(@Validated User user, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            for(FieldError fieldError:bindingResult.getFieldErrors()){
                logger.error(fieldError.toString());
            }
        }
        return userService.updateUser(user);
    }

    @RequestMapping("/deleteUser")
    @RequiresPermissions("second:no")
    public Object deleteUser(String id) {
        return userService.deleteUser(id);
    }
}
